#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Flask中间件
处理请求预处理和响应后处理
"""

from flask import request, g, jsonify
from functools import wraps
import time
import logging
from utils.response_helper import error_response

# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)


def before_request():
    """请求前处理"""
    g.start_time = time.time()
    
    # 记录请求信息
    logger.info(f"{request.method} {request.path} - IP: {request.remote_addr}")
    
    # 检查Content-Type（对于POST/PUT请求）
    if request.method in ['POST', 'PUT', 'PATCH']:
        if not request.is_json:
            return error_response('Content-Type must be application/json', 400)


def after_request(response):
    """请求后处理"""
    # 计算请求处理时间
    if hasattr(g, 'start_time'):
        duration = time.time() - g.start_time
        logger.info(f"Request completed in {duration:.3f}s - Status: {response.status_code}")
    
    # 添加安全头
    response.headers['X-Content-Type-Options'] = 'nosniff'
    response.headers['X-Frame-Options'] = 'DENY'
    response.headers['X-XSS-Protection'] = '1; mode=block'
    
    return response


def require_json(f):
    """装饰器：要求请求必须是JSON格式"""
    @wraps(f)
    def decorated_function(*args, **kwargs):
        if not request.is_json:
            return error_response('Content-Type must be application/json', 400)
        return f(*args, **kwargs)
    return decorated_function


def rate_limit(max_requests_per_minute=60):
    """简单的速率限制装饰器"""
    def decorator(f):
        @wraps(f)
        def decorated_function(*args, **kwargs):
            # 这里可以实现更复杂的速率限制逻辑
            # 目前仅作为示例
            return f(*args, **kwargs)
        return decorated_function
    return decorator


def log_request(f):
    """装饰器：记录请求详情"""
    @wraps(f)
    def decorated_function(*args, **kwargs):
        start_time = time.time()
        
        # 记录请求开始
        logger.info(f"Starting {request.method} {request.path}")
        
        try:
            result = f(*args, **kwargs)
            duration = time.time() - start_time
            logger.info(f"Completed {request.method} {request.path} in {duration:.3f}s")
            return result
        except Exception as e:
            duration = time.time() - start_time
            logger.error(f"Error in {request.method} {request.path} after {duration:.3f}s: {str(e)}")
            raise
            
    return decorated_function